package com.heima.common.exception;

import com.heima.common.dtos.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 处理Throwable的处理器，做一个兜底处理
     * @param e
     * @return
     */
    @ExceptionHandler(Throwable.class)
    public ResponseResult handlerException(Throwable e){
        log.error("全局异常处理器，异常堆栈:{}", ExceptionUtils.getStackTrace(e));
        return ResponseResult.error(AppHttpCodeEnum.SERVER_ERROR);
    }

    /**
     * 处理Leadexception的处理器
     * @param e
     * @return
     */
    @ExceptionHandler(LeadException.class)
    public ResponseResult handlerException(LeadException e){
        return ResponseResult.error(e.getStatus(), e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult paramException(MethodArgumentNotValidException e) {
        // 记录日志
        log.error(e.getMessage());
        // 返回通用异常信息
        return ResponseResult.error(AppHttpCodeEnum.PARAM_INVALID, e.getBindingResult().getFieldError().getDefaultMessage());
    }
}
